package com.tamo.ppresta.fragment;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.cardview.widget.CardView;
import androidx.core.content.FileProvider;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.http.EasyHttp;
import com.hjq.http.body.JsonBody;
import com.hjq.http.listener.OnHttpListener;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.tamo.ppresta.R;
import com.tamo.ppresta.activity.AboutUsActivity;
import com.tamo.ppresta.activity.FeedbackActivity;
import com.tamo.ppresta.activity.LoanDocumentationActivity;
import com.tamo.ppresta.activity.SendMessageActivity;
import com.tamo.ppresta.base.BaseApplication;
import com.tamo.ppresta.bean.GetMineInfoBean;
import com.tamo.ppresta.constant.NET_CONSTANT;
import com.tamo.ppresta.constant.SPConstant;
import com.tamo.ppresta.event.UserPhotoEvent;
import com.tamo.ppresta.http.HttpData;
import com.tamo.ppresta.httpapi.GetMineInfoApi;
import com.tamo.ppresta.json.ObjectToJsonUtil;
import com.tamo.ppresta.util.AESUtils;
import com.tamo.ppresta.util.ButtonUtils;
import com.tamo.ppresta.util.LogUtils;
import com.tamo.ppresta.util.MapUtils;
import com.tamo.ppresta.util.SPUtil;
import com.tamo.ppresta.util.ToastUtil;
import com.yalantis.ucrop.UCrop;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;
import okhttp3.Call;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AccountFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AccountFragment extends Fragment {
    private static String TAG = AccountFragment.class.getSimpleName();

    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.rl_zhanghu_kefu)
    RelativeLayout mRlZhanghuKefu;
    @BindView(R.id.iv_tip_icon)
    ImageView mIvTipIcon;
    @BindView(R.id.iv_tip_right)
    ImageView mIvTipRight;
    @BindView(R.id.tv_tip_text)
    TextView mTvTipText;
    @BindView(R.id.rl_zhanghu_tip)
    RelativeLayout mRlZhanghuTip;
    @BindView(R.id.iv_bancaria)
    ImageView mIvBancaria;
    @BindView(R.id.iv_bancaria_right)
    ImageView mIvBancariaRight;
    @BindView(R.id.rl_bancaria)
    RelativeLayout mRlBancaria;
    @BindView(R.id.iv_daikuanjilu)
    ImageView mIvDaikuanjilu;
    @BindView(R.id.iv_iv_daikuanjilu_right)
    ImageView mIvIvDaikuanjiluRight;
    @BindView(R.id.rl_daikuanjilu)
    RelativeLayout mRlDaikuanjilu;
    @BindView(R.id.cardview_one)
    CardView mCardviewOne;
    @BindView(R.id.iv_yijianfankui)
    ImageView mIvYijianfankui;
    @BindView(R.id.iv_yijianfankui_right)
    ImageView mIvYijianfankuiRight;
    @BindView(R.id.rl_yijianfankui)
    RelativeLayout mRlYijianfankui;
    @BindView(R.id.iv_yinsixieyi)
    ImageView mIvYinsixieyi;
    @BindView(R.id.iv_iv_yinsixieyi_right)
    ImageView mIvIvYinsixieyiRight;
    @BindView(R.id.rl_yinsixieyi)
    RelativeLayout mRlYinsixieyi;
    @BindView(R.id.iv_guanyuwomen)
    ImageView mIvGuanyuwomen;
    @BindView(R.id.iv_iv_guanyuwomen_right)
    ImageView mIvIvGuanyuwomenRight;
    @BindView(R.id.rl_guanyuwomen)
    RelativeLayout mRlGuanyuwomen;
    @BindView(R.id.cardview_two)
    CardView mCardviewTwo;
    @BindView(R.id.iv_zhanghu_banner)
    ImageView mIvZhanghuBanner;
    @BindView(R.id.tv_zhanghu_banner)
    TextView mTvZhanghuBanner;
    @BindView(R.id.cardview_three)
    CardView mCardviewThree;
    @BindView(R.id.tv_user_name)
    TextView mTvUserName;
    @BindView(R.id.iv_user_photo)
    CircleImageView mIvUserPhoto;
    @BindView(R.id.rl_content)
    RelativeLayout mRlContent;

    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private Unbinder unbinder;

    public static final int REQUEST_CODE_CAMERA = 103; //相机
    public static final int REQUEST_CODE_ALBUM = 102; //相册

    private Uri photoUri;//记录图片地址
    private Intent mIntentData = null;

    public AccountFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment HomeFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static AccountFragment newInstance(String param1, String param2) {
        AccountFragment fragment = new AccountFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_account, container, false);
        //返回一个unbinder对象，
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ImmersionBar.with(this)
                .statusBarColor(R.color.white)
                .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                .statusBarDarkFont(true)
                .init();
        EventBus.getDefault().register(this);
        mIvUserPhoto.setOnClickListener(this::onClick);
        mRlZhanghuKefu.setOnClickListener(this::onClick);
        mRlZhanghuTip.setOnClickListener(this::onClick);
        mRlBancaria.setOnClickListener(this::onClick);
        mRlDaikuanjilu.setOnClickListener(this::onClick);
        mRlYijianfankui.setOnClickListener(this::onClick);
        mRlYinsixieyi.setOnClickListener(this::onClick);
        mRlGuanyuwomen.setOnClickListener(this::onClick);
    }

    /**
     * 获取个人信息
     */
//    private void getMineInfo() {
//        String privateKey = AESUtils.getPrivateKey(24);
//        String privateKeyFront = AESUtils.getPrivateKeyFront(privateKey);
//        String privateKeyBehind = AESUtils.getPrivateKeyBehind(privateKey);
//        LogUtils.info(TAG, "随机秘钥：" + privateKey);
//        LogUtils.info(TAG, "随机秘钥19：" + privateKeyFront);
//        LogUtils.info(TAG, "随机秘钥5：" + privateKeyBehind);
//        BaseApplication.getInstance().setEasyHttpHead(NET_CONSTANT.HEADER_SECRETKEY_NAME, privateKeyFront);
//        GetMineInfoApi getMineInfoApi = new GetMineInfoApi().setLanguageCode(NET_CONSTANT.LANGUAGE_CODE)
//                .setItemCode(NET_CONSTANT.ITEM_CODE)
//                .setSessionId(SPUtil.getString(getContext(), SPConstant.SP_NAME, SPConstant.SP_SESSIONID))
//                .setProductItemCode(NET_CONSTANT.PRODUCTITEM_CODE);
//
//        Map<String, Object> stringObjectMap = MapUtils.objectToMap(getMineInfoApi);
//        String json = ObjectToJsonUtil.getJson(stringObjectMap);
//        LogUtils.info(TAG, json);
//        String newJson = ObjectToJsonUtil.getNewJson(stringObjectMap);
//        LogUtils.info(TAG, newJson);
//        String aesEncrypt = AESUtils.aesEncrypt(newJson, privateKey, NET_CONSTANT.VIPARR);
//        LogUtils.info(TAG, "加密： " + aesEncrypt);
//        String aesDecrypt = AESUtils.aesDecrypt(aesEncrypt, privateKey, NET_CONSTANT.VIPARR);
//        LogUtils.info(TAG, "解密： " + aesDecrypt);
//        EasyHttp.post(this).api(new GetMineInfoApi()).body(new JsonBody(aesEncrypt + privateKeyBehind)
//
//        ).request(new OnHttpListener<HttpData<GetMineInfoBean>>() {
//            @Override
//            public void onStart(Call call) {
//                LogUtils.info(TAG, "onStart: ");
//            }
//
//            @Override
//            public void onSucceed(HttpData<GetMineInfoBean> result, boolean cache) {
//                LogUtils.info(TAG, "onSucceed原始: " + result);
//                String data = result.toString();
//            }
//
//            @Override
//            public void onEnd(Call call) {
//                LogUtils.info(TAG, "onEnd: ");
//            }
//
//            @Override
//            public void onSucceed(HttpData<GetMineInfoBean> data) {
//                LogUtils.info(TAG, "data: " + data);
//            }
//
//            @Override
//            public void onFail(Exception e) {
//                LogUtils.info(TAG, "e: " + e.toString());
//            }
//        });
//    }

    private void onClick(View view) {
        ButtonUtils.isFastDoubleClick();
        switch (view.getId()) {
            case R.id.iv_user_photo:
                showBottomDialog();
                break;
            case R.id.rl_zhanghu_kefu:
                ToastUtil.showShort(getActivity(), "客服电话");
                getActivity().startActivity(new Intent(getActivity(), SendMessageActivity.class));
                break;
            case R.id.rl_zhanghu_tip:
                ToastUtil.showShort(getActivity(), "账户提示");
                break;
            case R.id.rl_bancaria:
                ToastUtil.showShort(getActivity(), "银行卡");
                break;
            case R.id.rl_daikuanjilu:
                getActivity().startActivity(new Intent(getActivity(), LoanDocumentationActivity.class));
                break;
            case R.id.rl_yijianfankui:
                getActivity().startActivity(new Intent(getActivity(), FeedbackActivity.class));
                break;
            case R.id.rl_yinsixieyi:
                ToastUtil.showShort(getActivity(), "隐私协议");
                break;
            case R.id.rl_guanyuwomen:
                getActivity().startActivity(new Intent(getActivity(), AboutUsActivity.class));
                break;

        }
    }

    // 裁剪方法
    private void doCrop(Uri data) {
        UCrop.of(data, getDestinationUri())//当前资源，保存目标位置
                .withAspectRatio(1f, 1f)//宽高比
                .withMaxResultSize(500, 500)//宽高
                .start(getActivity());
    }

    private Uri getDestinationUri() {
        String fileName = String.format("fr_crop_%s.jpg", System.currentTimeMillis());
        File cropFile = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
        return Uri.fromFile(cropFile);
    }

    private void showBottomDialog() {
        // 使用Dialog、设置style
        final Dialog dialog = new Dialog(getActivity(), R.style.DialogTheme);
        // 设置布局
        View view = View.inflate(getActivity(), R.layout.dialog_bottom_menu, null);
        dialog.setContentView(view);

        Window window = dialog.getWindow();
        // 设置弹出位置
        window.setGravity(Gravity.BOTTOM);
        // 设置弹出动画
        window.setWindowAnimations(R.style.main_menu_animStyle);
        // 设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();

        dialog.findViewById(R.id.tv_take_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 判断是否有相机权限
                ifHaveCameraPermission();
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.tv_take_pic).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 判断是否有文件存储权限
                ifHaveAlbumPermission();
                dialog.dismiss();
            }
        });

        dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });

    }

    // 判断是否有相机权限
    private void ifHaveCameraPermission() {
        XXPermissions.with(getActivity())
                // 申请单个权限
                .permission(Permission.CAMERA)
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean all) {
                        // 有权限 打开相机
                        openCamera();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtil.showShort(getContext(), "被永久拒绝授权，请手动打开相机权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getActivity(), permissions);
                        } else {
                            ToastUtil.showShort(getContext(), "获取相机权限失败");
                        }
                    }
                });
    }

    // 打开相机
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Build.VERSION.SDK_INT：获取当前系统sdk版本
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            // 适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
            String fileName = String.format("fr_crop_%s.jpg", System.currentTimeMillis());
            File cropFile = new File(getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES), fileName);
            photoUri = FileProvider.getUriForFile(getActivity(), getActivity().getPackageName() + ".FileProvider", cropFile);//7.0
        } else {
            photoUri = getDestinationUri();
        }
        // android11以后强制分区存储，外部资源无法访问，所以添加一个输出保存位置，然后取值操作
        intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
        startActivityForResult(intent, REQUEST_CODE_CAMERA);
    }

    // 判断是否有文件存储权限
    private void ifHaveAlbumPermission() {
        XXPermissions.with(getActivity())
                // 申请单个权限
                .permission(Permission.Group.STORAGE)
                // 设置不触发错误检测机制（局部设置）
                //.unchecked()
                .request(new OnPermissionCallback() {

                    @Override
                    public void onGranted(@NonNull List<String> permissions, boolean all) {
                        // 有权限 打开相册
                        openAlbum();
                    }

                    @Override
                    public void onDenied(@NonNull List<String> permissions, boolean never) {
                        if (never) {
                            ToastUtil.showShort(getContext(), "被永久拒绝授权，请手动打开相册权限");
                            // 如果是被永久拒绝就跳转到应用权限系统设置页面
                            XXPermissions.startPermissionActivity(getActivity(), permissions);
                        } else {
                            ToastUtil.showShort(getContext(), "获取相册权限失败");
                        }
                    }
                });
    }

    // 打开相册
    private void openAlbum() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction("android.intent.action.GET_CONTENT");
        intent.addCategory("android.intent.category.OPENABLE");
        startActivityForResult(intent, REQUEST_CODE_ALBUM);
    }

    @RequiresApi(api = Build.VERSION_CODES.Q)
    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.info(TAG, "页面返回: " + requestCode);
        mIntentData = data;
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_ALBUM:
                    LogUtils.info(TAG, "uri: " + data.getData());
                    doCrop(data.getData());
                    break;
                case REQUEST_CODE_CAMERA:
                    LogUtils.info(TAG, "uri: " + photoUri);
                    doCrop(photoUri);
                    break;
//                case UCrop.REQUEST_CROP:
//                    LogUtils.info(TAG, "uri: " + UCrop.getOutput(data));
//                    Glide.with(getActivity()).load(UCrop.getOutput(data)).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(mIvUserPhoto);
//                    break;
            }
        }
        if (resultCode == UCrop.RESULT_ERROR) {
            final Throwable cropError = UCrop.getError(data);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
//        getMineInfo();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        //进行判空，避免空指针
        if (unbinder != null) {
            unbinder.unbind();
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void setUserPhotoEvent(UserPhotoEvent userPhotoEvent) {
        LogUtils.info(TAG, "setUserPhotoEvent");
        if (null != mIvUserPhoto) {
            LogUtils.info(TAG, "setUserPhotoEvent: " + mIntentData.getData());
            Glide.with(getActivity()).load(mIntentData.getData()).apply(RequestOptions.bitmapTransform(new CircleCrop())).into(mIvUserPhoto);
        }
    }
}